"use client"

import { useState, useEffect } from "react"
import type { Playlist } from "@/types/playlist"
import { PlaylistCard } from "@/components/playlist-card"
import { Pagination } from "@/components/ui/pagination"
import { Skeleton } from "@/components/ui/skeleton"
import {fetchPlaylist} from "@/lib/api-client";

interface PlaylistGridProps {
  selectedCategory: number | string | null
}

export function PlaylistGrid({ selectedCategory }: PlaylistGridProps) {
  const [playlists, setPlaylists] = useState<Playlist[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const limit = 5 // 每页显示的歌单数量

  // 当分类或页码变化时获取歌单
  useEffect(() => {
    const fetchPlaylists = async () => {
      setIsLoading(true)
      try {
        // 构建查询参数
        const params: any = {
          page,
          limit,
        }

        // 如果有选中的分类，添加到查询参数
        if (selectedCategory !== null) {
          params.categoryId = selectedCategory
        }
        const userId = localStorage.getItem("userId")
        if (userId){
          params.userId = userId
        }
        // 发起API请求
        const response = await fetchPlaylist(params)

        if (response.success) {
          setPlaylists(response.data.items || [])
          setTotalPages(response.data.totalPages || 1)
        } else {
          console.error("获取歌单失败:", response.data?.message)
          setPlaylists([])
        }
      } catch (error) {
        console.error("获取歌单出错:", error)
        setPlaylists([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchPlaylists()
  }, [selectedCategory, page])

  // 处理页码变化
  const handlePageChange = (newPage: number) => {
    setPage(newPage)
    // 滚动到页面顶部
    window.scrollTo({ top: 0, behavior: "smooth" })
  }

  if (isLoading) {
    return (
        <div className="mt-8 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
          {Array.from({ length: 5 }).map((_, index) => (
              <div key={index} className="space-y-3">
                <Skeleton className="h-40 w-full rounded-md" />
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-2/3" />
              </div>
          ))}
        </div>
    )
  }

  if (playlists.length === 0) {
    return (
        <div className="mt-8 flex h-40 items-center justify-center rounded-md border border-dashed">
          <p className="text-center text-muted-foreground">暂无歌单</p>
        </div>
    )
  }

  return (
      <div className="space-y-6">
        <div className="mt-8 grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
          {playlists.map((playlist) => (
              <PlaylistCard key={playlist.id} playlist={playlist} showCreator={true}/>
          ))}
        </div>

        {totalPages > 1 && (
            <div className="flex justify-center mt-8">
              <Pagination currentPage={page} totalPages={totalPages} onPageChange={handlePageChange} />
            </div>
        )}
      </div>
  )
}

